<?php
/*
  [EWEISHOP] Copyright(C) 2017 Elinkint Inc.
  This is NOT a freeware, use is subject to license terms
   
  OfficialAccountOAuth.php 2018-05-25 14:43 likexin
   
*/

namespace common\library\wechat\officialaccount;

use common\library\wechat\WechatApi;
use common\component\wechat\Wechat;
use Overtrue\Socialite\AuthorizeFailedException;

class OfficialAccountOAuth extends WechatApi
{

    /**
     * OAuth跳转
     * @param array $scopes 覆盖权限 [snsapi_base, snsapi_userinfo, snsapi_login]
     * @param null $redirectUrl 回调URL
     * @return mixed
     * @link https://www.easywechat.com/docs/master/zh-CN/official-account/oauth
     */
    public static function redirect($scopes = [], $redirectUrl = null)
    {
        $oauth = self::getInstance()->oauth;
        if(!empty($scopes)) {
            $oauth = $oauth->scopes($scopes);
        }
        if(!empty($redirectUrl)){
            $oauth = $oauth->setRedirectUrl($redirectUrl);
        }
        $response = $oauth->redirect();
        return $response->send();
    }

    /**
     * 获取用户(用户OAuth回调后使用)
     * @link https://www.easywechat.com/docs/master/zh-CN/official-account/oauth
     */
    public static function user()
    {
        $oauth = self::getInstance()->oauth;
        try {
            $user = $oauth->user();
        } catch (AuthorizeFailedException $exception){
            return error($exception->getMessage());
        }
        return Wechat::apiError($user->toArray());
    }

}